<?php
namespace app\mini\model;

use app\admin\model\PersonModel;
use app\crm\model\Customer;
use app\mini\controller\QyWechatController;
use think\facade\Db;
use app\common\traits\ActionRecordTrait;
use think\Model;
use app\admin\controller\ApiCommon;
//use app\mini\controller\QyWechatController;

use app\crm\model\CustomerLossModel;
use app\crm\model\OrderStatistics;
use app\admin\model\ShopOrderModel;
use app\admin\model\CustomerModel;
use app\admin\model\ShopModel;
use app\shop\model\Refund as OrderModel;
use app\mini\model\MiniStisticsModel;
use app\mini\model\CustomerPointGoodsBuy;
use app\admin\model\ShopOrderModel as AdminShopOrderModel;
use app\crm\model\ReserveandLost;


class SysModelMiniAdmin extends Model
{
    /**

     * @var string

     */

    protected $name = 'admin_sys';


    protected $defaultSoftDelete = 0;


    protected $autoWriteTimestamp = true;
 
    /**
     * 店均成交个数
     */
    public function getCJTotal($request):array
    {
        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $where_cj = [];
        $where_jd = [];

        if($start_time && $end_time){
            
            $start_time = strtotime($start_time);

            $end_time = strtotime($end_time)+86399;

            array_push($where_cj,['cj_time','between',"$start_time,$end_time"]);

            array_push($where_jd,['first_time|second_time','between',"$start_time,$end_time"]);

        }

        if($shop_ids){

            array_push($where_cj,['shop_id','in',$shop_ids]);

            array_push($where_jd,['shop_id','in',$shop_ids]);

        }

        $cj_num = Db::name('customer')->where($where_cj)->count();

        $jd_num = Db::name('customer')->where($where_jd)->count();

        $average_num = ceil($cj_num/count($shop_ids));

        $average_cj_rate = sprintf("%.1f", (($cj_num/$jd_num)*100));

        // 计算均单值
        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);
        array_push($where,['deal_time','between',"$start_time,$end_time"]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['order_type','=',1]);
        array_push($where,['refund_type','=','101.02 ']);

        $shoukuan = Db::name('shop_refund_order')->where($where)->column('SUM(pay_amount)');

        // echo "<pre>";
        // print_r($shoukuan);
        // echo "</pre>";
        // exit;


        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);
        array_push($where,['deal_time','between',"$start_time,$end_time"]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',2]);
        array_push($where,['order_type','=',1]);
        array_push($where,['refund_type','=','101.02 ']);

        $tuikuan = Db::name('shop_refund_order')->where($where)->column('SUM(pay_amount)');

        $shishou = bcsub($shoukuan[0],$tuikuan[0],2);

        $res = bcdiv($shishou,$cj_num);

        $jundanzhi = bcdiv($res,10000,2);

        return [

            'average_num' => $average_num,

            'average_cj_rate' => $average_cj_rate,

            'jundanzhi' => $jundanzhi,

        ];
    }

    // 成交数据-市场/门店业绩
    public function getcjGrade($request):array
    {

        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $type = $request['type'] ?? '1';

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;

        if($type == '1'){ // 市场维度查询

            $market_list = Db::name('shop')->where('shop_id','in',$shop_ids)->column('market_id','shop_id');

            $shop_names = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name','shop_id');

            $market_ids = [];

            foreach ($market_list as $key => $value) {
                
                if(in_array($value,$market_ids)){

                }else{
                    array_push($market_ids,$value);
                }

            }

            $market_name = Db::name('shop_market')->where([['id','in',$market_ids]])->column('name,other_name','id');

            $list = [];

            foreach ($market_ids as $key => $value) {

                $one = [];

                $one['market_id'] = $value;

                $one['market_name'] = $market_name[$value]['name'];

                $one['other_name'] = $market_name[$value]['other_name'];

                $one['shop_list'] = [];
                
                foreach ($market_list as $k => $v) {
                    
                    if($v == $value){

                        array_push($one['shop_list'],$k);

                    }

                }

                array_push($list,$one);

            }

            foreach ($list as $key => $value) {
                
                $where = [];

                array_push($where,['shop_id','in',$value['shop_list']]);
                array_push($where,['cj_time','between',"$start_time,$end_time"]);

                $cj_num = Db::name('customer')->where($where)->count();


                $where = [];

                array_push($where,['shop_id','in',$value['shop_list']]);
                array_push($where,['first_time|second_time','between',"$start_time,$end_time"]);
                
                $jd_num = Db::name('customer')->where($where)->count();

                
                // $where = [];

                // array_push($where,['shop_id','in',$value['shop_list']]);
                // array_push($where,['deal_time','between',"$start_time,$end_time"]);
                // array_push($where,['status','=',2]);
                // array_push($where,['type','=',3]);
                // array_push($where,['order_type','=',1]);
                // array_push($where,['refund_type','=','101.02 ']);

                // $shoukuan = Db::name('shop_refund_order')->where($where)->column('SUM(pay_amount)');


                $where = [];

                array_push($where,['shop_id','in',$value['shop_list']]);
                array_push($where,['deal_time','between',"$start_time,$end_time"]);
                array_push($where,['status','=',2]);
                array_push($where,['type','=',3]);
                array_push($where,['order_type','=',1]);
                array_push($where,['refund_type','=','101.02 ']);

                $shoukuan = Db::name('shop_refund_order')->where($where)->column('SUM(pay_amount)');
                

                $where = [];

                array_push($where,['shop_id','in',$value['shop_list']]);
                array_push($where,['deal_time','between',"$start_time,$end_time"]);
                array_push($where,['status','=',2]);
                array_push($where,['type','=',2]);
                array_push($where,['order_type','=',1]);
                array_push($where,['refund_type','=','101.02 ']);

                $tuikuan = Db::name('shop_refund_order')->where($where)->column('SUM(pay_amount)');

                $shishou = bcsub($shoukuan[0],$tuikuan[0],2);

                $res = bcdiv($shishou,$cj_num);

                $jundanzhi = bcdiv($res,10000,2);

                $list[$key]['cj_num'] = $cj_num;
                $list[$key]['cj_rate'] = sprintf('%.1f',(($cj_num/$jd_num)*100)).'%';
                $list[$key]['jundan'] = $jundanzhi;

            }
            
            return [
                'list' => $list,
                'type' => '1',
            ];

        }


        if($type == '2'){

            // echo "门店维度查询";

            $shop_name = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name,shop_othername','shop_id');

            $where = [];

            array_push($where,['shop_id','in',$shop_ids]);
            array_push($where,['first_time|second_time','between',"$start_time,$end_time"]);
            
            $jd_res = Db::name('customer')->where($where)->group('shop_id')->column('count(id)','shop_id');

            $where = [];

            array_push($where,['shop_id','in',$shop_ids]);
            array_push($where,['cj_time','between',"$start_time,$end_time"]);
            
            $cj_res = Db::name('customer')->where($where)->group('shop_id')->column('count(id)','shop_id');

            $list = [];

            foreach ($shop_name as $key => $value) {

                $one = [];

                $one['shop_name'] = $value['shop_name'];
                $one['other_name'] = $value['shop_othername'];
                $one['cj'] = $cj_res[$key] ?? '0';
                $one['jd'] = $jd_res[$key] ?? '0';

                $cj_rate = $jd_res[$key] > 0 ? (bcdiv($cj_res[$key],$jd_res[$key],3))*100 : '';
                $one['cj_rate'] = sprintf('%.1f',$cj_rate);

                array_push($list,$one);

            }

            return [
                'list' => $list,
                'type' => '2',
            ];


        }

        
    }


    // ----------------------------------------------------体验成交--------------------------------------------
    public function getTiyanChengjiaoGrade($request)
    {

        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $type = $request['type'] ?? '1';

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;

        if($type == '1'){ // 市场维度查询

            $market_list = Db::name('shop')->where('shop_id','in',$shop_ids)->column('market_id','shop_id');

            $shop_names = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name','shop_id');

            $market_ids = [];

            foreach ($market_list as $key => $value) {
                
                if(in_array($value,$market_ids)){

                }else{
                    array_push($market_ids,$value);
                }

            }

            $market_name = Db::name('shop_market')->where([['id','in',$market_ids]])->column('name,other_name','id');

            $list = [];

            foreach ($market_ids as $key => $value) {

                $one = [];

                $one['market_id'] = $value;

                $one['market_name'] = $market_name[$value]['name'];

                $one['other_name'] = $market_name[$value]['other_name'];

                $one['shop_list'] = [];
                
                foreach ($market_list as $k => $v) {
                    
                    if($v == $value){

                        array_push($one['shop_list'],$k);

                    }

                }

                array_push($list,$one);

            }

            foreach ($list as $key => $value) {

                $experience_good = [150,168,165,686];
                //查询销售出库单中的是否体验个数---2022.04.11 修改

                // 体验顾客（指定时间内）
                $tiyanNum = Db::name('service_log')->where([['create_time', 'between', [$start_time,$end_time]], ['goods_id', 'in', $experience_good],['shop_id','in',$value['shop_list']]])->count();

                // 体验顾客（包括以往）
                $tiyan_customerids = Db::name('service_log')->where([['goods_id', 'in', $experience_good],['shop_id','in',$value['shop_list']]])->column('customer_id');

                $tiyanCjNum = Db::name('customer')->where([['cj_time','between',"$start_time,$end_time"],['id','in',$tiyan_customerids]])->count();

                $list[$key]['tiyanNum'] = $tiyanNum;
                $list[$key]['tiyanCjNum'] = $tiyanCjNum;
                $list[$key]['ty_cj_rate'] = $tiyanNum > 0 ? sprintf('%.1f',(($tiyanCjNum/$tiyanNum)*100)).'%' : '0%';

            }


        }

        if($type == '2'){
            // echo "门店维度查询";

            $shop_name = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name,shop_othername','shop_id');

            $list = [];

            foreach ($shop_name as $key => $value) {

                $experience_good = [150,168,165,686];
                //查询销售出库单中的是否体验个数---2022.04.11 修改

                // 体验顾客（指定时间内）
                $tiyanNum = Db::name('service_log')->where([['create_time', 'between', [$start_time,$end_time]], ['goods_id', 'in', $experience_good],['shop_id','=',$key]])->count();

                // 体验顾客（包括以往）
                $tiyan_customerids = Db::name('service_log')->where([['goods_id', 'in', $experience_good],['shop_id','=',$key]])->column('customer_id');

                $tiyanCjNum = Db::name('customer')->where([['cj_time','between',"$start_time,$end_time"],['id','in',$tiyan_customerids]])->count();

                $one = [];

                $one['shop_name'] = $value['shop_name'];
                $one['other_name'] = $value['shop_othername'];
                $one['tiyanNum'] = $tiyanNum;
                $one['tiyanCjNum'] = $tiyanCjNum;
                $one['ty_cj_rate'] = $tiyanNum > 0 ? sprintf('%.1f',(($tiyanCjNum/$tiyanNum)*100)).'%' : '0%';

                array_push($list,$one);

            }
        }

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";
        // exit;

        return [
            'list' => $list,
            'type' => $type,
        ];
        
    }

    // 成交分类
    public function getMarketCJtypeRate($request)
    {

        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $type = $request['type'] ?? '1';

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;

        $model = new AdminShopOrderModel();

        $inputArr = [];

        $inputArr['startTime'] = $request['start_time'];
        $inputArr['endTime'] = $request['end_time'];

        if($type == '1'){ // 市场维度查询

            $market_list = Db::name('shop')->where('shop_id','in',$shop_ids)->column('market_id','shop_id');

            $shop_names = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name','shop_id');

            $market_ids = [];

            foreach ($market_list as $key => $value) {
                
                if(in_array($value,$market_ids)){

                }else{
                    array_push($market_ids,$value);
                }

            }

            $market_name = Db::name('shop_market')->where([['id','in',$market_ids]])->column('name,other_name','id');

            $list = [];

            foreach ($market_ids as $key => $value) {

                $one = [];

                $one['market_id'] = $value;

                $one['market_name'] = $market_name[$value]['name'];

                $one['other_name'] = $market_name[$value]['other_name'];

                $one['shop_list'] = [];
                
                foreach ($market_list as $k => $v) {
                    
                    if($v == $value){

                        array_push($one['shop_list'],$k);

                    }

                }

                array_push($list,$one);

            }

            foreach ($list as $key => $value) {

                $res = $model->getShopOrderCommonDataCollect($value['shop_list'],$inputArr);

                $cjTotle = $res['sysDealNumber'];

                $bh = $res['sysDealNumberEcharts'][0]['value'];
                $dd = $res['sysDealNumberEcharts'][1]['value'];
                $xm = $res['sysDealNumberEcharts'][2]['value'];
                
                $list[$key]['bh'] = $bh;
                $list[$key]['bh_rate'] = $cjTotle>0 ? sprintf('%.1f',(($bh/$cjTotle)*100)).'%' : '0%';

                $list[$key]['dd'] = $dd;
                $list[$key]['dd_rate'] = $cjTotle>0 ? sprintf('%.1f',(($dd/$cjTotle)*100)).'%' : '0%';

                $list[$key]['xm'] = $xm;
                $list[$key]['xm_rate'] = $cjTotle>0 ? sprintf('%.1f',(($xm/$cjTotle)*100)).'%' : '0%';


                // echo "<pre>";
                // print_r($res);
                // echo "</pre>";
                // exit;

            }


        }

        if($type == '2'){ // 市场维度查询

            $shop_name = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name,shop_othername','shop_id');

            $list = [];

            foreach ($shop_name as $key => $value) {

                $shop_ids = [];

                array_push($shop_ids,$key);

                $res = $model->getShopOrderCommonDataCollect($shop_ids,$inputArr);

                $cjTotle = $res['sysDealNumber'];

                $bh = $res['sysDealNumberEcharts'][0]['value'];
                $dd = $res['sysDealNumberEcharts'][1]['value'];
                $xm = $res['sysDealNumberEcharts'][2]['value'];
                
                

                $one = [];

                $one['shop_name'] = $value['shop_name'];
                $one['other_name'] = $value['shop_othername'];
                $one['bh'] = $bh;
                $one['bh_rate'] = $cjTotle>0 ? sprintf('%.1f',(($bh/$cjTotle)*100)).'%' : '0%';

                $one['dd'] = $dd;
                $one['dd_rate'] = $cjTotle>0 ? sprintf('%.1f',(($dd/$cjTotle)*100)).'%' : '0%';

                $one['xm'] = $xm;
                $one['xm_rate'] = $cjTotle>0 ? sprintf('%.1f',(($xm/$cjTotle)*100)).'%' : '0%';

                array_push($list,$one);

            }

        }

        return [
            'list' => $list,
            'type' => $type,
        ];
        
    }

    // 客户数据-客户数据（echarts）
    public function getComeInEcharts($request)
    {
        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;

        $xianshang    = [43,44,50,51,52,53,54,55,56,118,609];
        $mentou       = [47];
        $wailian      = [46];
        $ditui        = [48];
        $zhuanjieshao = [49];

        // 线上进店
        $comein_xianshang = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','in',$shop_ids],['source_id','in',$xianshang]])->count();

        // 外联进店
        $comein_wailian = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','in',$shop_ids],['source_id','in',$wailian]])->count();

        // 门头进店
        $comein_mentou = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','in',$shop_ids],['source_id','in',$mentou]])->count();

        // 地推进店
        $comein_ditui = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','in',$shop_ids],['source_id','in',$ditui]])->count();

        // 转介绍进店
        $comein_zhuanjieshao = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','in',$shop_ids],['source_id','in',$zhuanjieshao]])->count();

        $comein_all = $comein_xianshang+$comein_wailian+$comein_mentou+$comein_ditui+$comein_zhuanjieshao;


        $xs_rate = $comein_all>0 ? sprintf('%.1f',(($comein_xianshang/$comein_all)*100)).'%' : '0%';

        $wl_rate = $comein_all>0 ? sprintf('%.1f',(($comein_wailian/$comein_all)*100)).'%' : '0%';

        $mt_rate = $comein_all>0 ? sprintf('%.1f',(($comein_mentou/$comein_all)*100)).'%' : '0%';

        $dt_rate = $comein_all>0 ? sprintf('%.1f',(($comein_ditui/$comein_all)*100)).'%' : '0%';

        $zjs_rate = $comein_all>0 ? sprintf('%.1f',(($comein_zhuanjieshao/$comein_all)*100)).'%' : '0%';

        

        // 'wl'       => $comein_wailian,
        // 'wl_rate'  => $wl_rate,

        // 'mt'       => $comein_mentou,
        // 'mt_rate'  => $mt_rate,

        // 'dt'       => $comein_ditui,
        // 'dt_rate'  => $dt_rate,

        // 'zjs'      => $comein_zhuanjieshao,
        // 'zjs_rate' => $zjs_rate,
        
        return [
            [
                'name'     => '线上',
                'value'    => $comein_xianshang,
                'rate'     => $xs_rate,
            ],
            [
                'name'     => '外联',
                'value'    => $comein_wailian,
                'rate'     => $wl_rate,
            ],
            [
                'name'     => '门头',
                'value'    => $comein_mentou,
                'rate'     => $mt_rate,
            ],
            [
                'name'     => '地推',
                'value'    => $comein_ditui,
                'rate'     => $dt_rate,
            ],
            [
                'name'     => '转介绍',
                'value'    => $comein_zhuanjieshao,
                'rate'     => $zjs_rate,
            ],
            
        ];
    }

    // 客户数据-进店数据（市场/门店列表）
    public function getComeInList($request)
    {

        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $type = $request['type'] ?? '1';

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;

        $xianshang    = [43,44,50,51,52,53,54,55,56,118,609];
        $xianxia      = [46,47,48];
        $zhuanjieshao = [49];

        if($type == 1){

            $list = $this->getMarketList($shop_ids);

            foreach ($list as $key => $value) {
                
                $xs = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','in',$value['shop_list']],['source_id','in',$xianshang]])->count();

                $xx = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','in',$value['shop_list']],['source_id','in',$xianxia]])->count();

                $zjs = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','in',$value['shop_list']],['source_id','in',$zhuanjieshao]])->count();

                $all = $xs+$xx+$zjs;

                $list[$key]['xs']  = $xs;
                $list[$key]['xx']  = $xx;
                $list[$key]['zjs'] = $zjs;
                $list[$key]['all'] = $all;
                

            }

        }

        if($type == 2){
            
            $shop_name = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name,shop_othername','shop_id');

            $list = [];

            foreach ($shop_name as $key => $value) {

                $xs = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','=',$key],['source_id','in',$xianshang]])->count();

                $xx = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','=',$key],['source_id','in',$xianxia]])->count();

                $zjs = Db::name('customer')->where([['first_time|second_time','between',"$start_time,$end_time"],['shop_id','=',$key],['source_id','in',$zhuanjieshao]])->count();

                $all = $xs+$xx+$zjs;
                
                

                $one = [];

                $one['shop_name'] = $value['shop_name'];
                $one['other_name'] = $value['shop_othername'];
                $one['xs'] = $xs;
                $one['xx'] = $xx;
                $one['zjs'] = $zjs;
                $one['all'] = $all;
                

                array_push($list,$one);

            }
        }

        return [
            'list' => $list,
            'type' => $type,
        ];

    }

    // 客户数据
    public function getCustomerData($request)
    {

        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $type = $request['type'] ?? '1';

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;
        

        $today = date('Y-m-d');
        $byModel = new ReserveandLost();
        // 保有率-成交个数
        $cj_customer = $byModel->cj_customer($shop_ids,[]);

        // 保有顾客
        $by_customer = $byModel->baoyou_customer($cj_customer,$today);

        // 流失顾客
        $lost_customer = $byModel->lost_customer($cj_customer,$today);

        $by_rate = count($cj_customer)>0 ? sprintf('%.1f',((count($by_customer)/count($cj_customer))*100)).'%' : '0%';

        return [
            'by_num'  => count($by_customer),
            'ls_num'  => count($lost_customer),
            'by_rate' => $by_rate,
        ];
    }

    // 客户数据-会员分类和等级
    public function getCustomerType($request)
    {

        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $type = $request['type'] ?? '1';

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;
        
        $today = date('Y-m-d');
        $byModel = new ReserveandLost();
        // 保有率-成交个数
        $cj_customer = $byModel->cj_customer($shop_ids,[]);

        // 保有顾客
        $by_customer = $byModel->baoyou_customer($cj_customer,$today);

        $a = Db::name('customer')->where([['id','in',$by_customer],['member_classification','=',73]])->count();

        $b = Db::name('customer')->where([['id','in',$by_customer],['member_classification','=',72]])->count();
        
        $c = Db::name('customer')->where([['id','in',$by_customer],['member_classification','=',71]])->count();

        $gold = Db::name('customer')->where([['id','in',$by_customer],['membership_leve','=',3]])->count();

        $purple = Db::name('customer')->where([['id','in',$by_customer],['membership_leve','=',2]])->count();

        $white = Db::name('customer')->where([['id','in',$by_customer],['membership_leve','=',1]])->count();

        return [
            'A' => $a,
            'B' => $b,
            'C' => $c,
            'gold' => $gold,
            'purple' => $purple,
            'white' => $white,
        ];

    }


    // 客户数据-二次开发率/项目普及率/功效满意度
    public function getErci($request)
    {

        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $type = $request['type'] ?? '1';

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;

        $old_start_time=strtotime(date("Y-m-01 00:00:00",strtotime("-4 month",$start_time)));// 新单成交  开始时间
		$old_end_time=strtotime(date('Y-m-01', $old_start_time) . ' 1 month -1 day'. ' 23:59:59');//新单成交 成交结束时间

        //成交的疤痕顾客  business_type 1是疤痕
		$scarList = Db::name('customer')
            ->alias('b')
            ->where('b.cj_time','between',"$old_start_time,$old_end_time")//2022.01.01
            ->where('b.cj_money','>',0)
            ->leftjoin('shop_refund_order sp','b.cj_order_id = sp.id')
            ->where('sp.business_type','=',1)
            ->where('sp.type','=',3)
            ->where('sp.shop_id','in',$shop_ids)
            ->column('b.id,b.shop_id,b.cj_money,b.telephone');
        
        
        $model = new shopModel();

        $bahenNum =$model->redAdminProjectByShopId($scarList,$old_start_time,$old_end_time,$end_time);

        $xiangmNum =$model->redAdminXmByShopId($scarList,$old_start_time,$old_end_time,$end_time);

        $gxmanyiNum =$model->setGXmanyiCustomerShopList($scarList,$old_start_time,$old_end_time,$end_time);


        $developRate =count($scarList)>0 ? (bcdiv($bahenNum,count($scarList),3)*100).'%' :'0%';  //疤痘二次消费率
        $popularityRate =count($scarList)>0 ? (bcdiv($xiangmNum,count($scarList),3)*100).'%' :'0%'; //项目普及率
        $gongxiaomanyi =count($scarList)>0 ? (bcdiv($gxmanyiNum,count($scarList),3)*100).'%' :'0%'; //功效满意度

        

        return [
            'developRate' => $developRate,
            'popularityRate' => $popularityRate,
            'gongxiaomanyi' => $gongxiaomanyi,
        ];

    }

    // -----------------------------------------业绩数据--------------------------------------------------------
    public function getTotalPerformanceEcharts($request)
    {
        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;

        $market = $this->getMarketList($shop_ids);

        $model = new OrderStatistics();

        $xd = 0;
        $bd = 0;

        foreach ($market as $key => $value) {

            if($value['market_id'] == 8 || $value['market_id'] == 9 || $value['market_id'] == 10 || $value['market_id'] == 11){ // 川渝市场

                foreach ($value['shop_list'] as $k => $v) {

                    $shopIds = [];

                    array_push($shopIds,$v);

                    $newsXDMoneyAll =$model->sumShopPayMoneyNewMZAll('XD',$shopIds,$start_time,$end_time);
                    $budanMoneyAll =$model->sumShopPayMoneyNewMZAll('BD',$shopIds,$start_time,$end_time);

                    $newsXDMoney = empty($newsXDMoneyAll[$v])?0:$newsXDMoneyAll[$v];
                    $budanMoney = empty($budanMoneyAll[$v])?0:$budanMoneyAll[$v];

                    $xd = bcadd($xd,$newsXDMoney,2);
                    $bd = bcadd($bd,$budanMoney,2);

                }
                
            }else{ // 非川渝市场

                foreach ($value['shop_list'] as $k => $v) {

                    $shopIds = [];

                    array_push($shopIds,$v);

                    $shop_type = Db::name('shop')->where('shop_id',$v)->value('shop_type');
                    
                    if($shop_type == 1){

                        $newsXDMoneyAllOne =$model->sumShopPayMoneyNewAll('XD',$shopIds,1,$start_time,$end_time);
                        $budanMoneyAllOne =$model->sumShopPayMoneyNewAll('BD',$shopIds,1,$start_time,$end_time);

                        $newsXDMoney = empty($newsXDMoneyAllOne[$v])?0:$newsXDMoneyAllOne[$v];
                        $budanMoney = empty($budanMoneyAllOne[$v])?0:$budanMoneyAllOne[$v];

                    }else{

                        $newsXDMoneyAllTwo =$model->sumShopPayMoneyNewAll('XD',$shopIds,2,$start_time,$end_time);
                        $budanMoneyAllTwo =$model->sumShopPayMoneyNewAll('BD',$shopIds,2,$start_time,$end_time);

                        $newsXDMoney = empty($newsXDMoneyAllTwo[$v])?0:$newsXDMoneyAllTwo[$v];
                        $budanMoney = empty($budanMoneyAllTwo[$v])?0:$budanMoneyAllTwo[$v];

                    }

                    $xd = bcadd($xd,$newsXDMoney,2);
                    $bd = bcadd($bd,$budanMoney,2);
                    
                }

            }

        }

        $all = bcadd($xd,$bd,2);

        $xd_rate = $all>0 ? (bcdiv($xd,$all,3)*100).'%' :'0%';
        $bd_rate = $all>0 ? (bcdiv($bd,$all,3)*100).'%' :'0%';

        $xd = bcdiv($xd,10000,1);
        $bd = bcdiv($bd,10000,1);

        $data = [];

        $xd = [
            'name' => '新单业绩',
            'value' => $xd,
            'rate' => $xd_rate,
        ];

        $bd = [
            'name' => '补单业绩',
            'value' => $bd,
            'rate' => $bd_rate,
        ];

        array_push($data,$xd);
        array_push($data,$bd);

        return $data;
    }

    public function getTotalPerformance($request)
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;
        
        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $type = $request['type'] ?? '1';

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;

        $market = $this->getMarketList($shop_ids);

        $startMonthTime = strtotime(date('Y-m',$start_time));

        $endMonthTime = strtotime(date('Y-m',$end_time));

        $market_ids = array_values(array_unique(array_column($market,'market_id')));

        // 市场任务
        //门店当月市场任务

        $marketTask =Db::name('shop_task')
        
            // ->field('sum(price) as price,sum(price_base) as price_base,market_id')

            ->where('month','>=',$startMonthTime)

            ->where('month','<=',$endMonthTime)

            ->where('market_id','in',$market_ids)

            ->group('market_id')
            
            // ->select()->toArray();

            ->column('sum(price) as price','market_id');

        $model = new OrderStatistics();

        // echo "<pre>";
        // print_r($marketTask);
        // echo "</pre>";
        // exit;


        if($type == 1){

            
            foreach ($market as $key => $value) {

                $xd = 0;
                $bd = 0;

                if($value['market_id'] == 8 || $value['market_id'] == 9 || $value['market_id'] == 10 || $value['market_id'] == 11){ // 川渝市场

                    foreach ($value['shop_list'] as $k => $v) {

                        $shopIds = [];

                        array_push($shopIds,$v);

                        $newsXDMoneyAll =$model->sumShopPayMoneyNewMZAll('XD',$shopIds,$start_time,$end_time);
                        $budanMoneyAll =$model->sumShopPayMoneyNewMZAll('BD',$shopIds,$start_time,$end_time);

                        $newsXDMoney = empty($newsXDMoneyAll[$v])?0:$newsXDMoneyAll[$v];
                        $budanMoney = empty($budanMoneyAll[$v])?0:$budanMoneyAll[$v];

                        $xd = bcadd($xd,$newsXDMoney,2);
                        $bd = bcadd($bd,$budanMoney,2);

                    }
                    
                }else{ // 非川渝市场

                    foreach ($value['shop_list'] as $k => $v) {

                        $shopIds = [];

                        array_push($shopIds,$v);

                        $shop_type = Db::name('shop')->where('shop_id',$v)->value('shop_type');
                        
                        if($shop_type == 1){

                            $newsXDMoneyAllOne =$model->sumShopPayMoneyNewAll('XD',$shopIds,1,$start_time,$end_time);
                            $budanMoneyAllOne =$model->sumShopPayMoneyNewAll('BD',$shopIds,1,$start_time,$end_time);

                            $newsXDMoney = empty($newsXDMoneyAllOne[$v])?0:$newsXDMoneyAllOne[$v];
                            $budanMoney = empty($budanMoneyAllOne[$v])?0:$budanMoneyAllOne[$v];

                        }else{

                            $newsXDMoneyAllTwo =$model->sumShopPayMoneyNewAll('XD',$shopIds,2,$start_time,$end_time);
                            $budanMoneyAllTwo =$model->sumShopPayMoneyNewAll('BD',$shopIds,2,$start_time,$end_time);

                            $newsXDMoney = empty($newsXDMoneyAllTwo[$v])?0:$newsXDMoneyAllTwo[$v];
                            $budanMoney = empty($budanMoneyAllTwo[$v])?0:$budanMoneyAllTwo[$v];

                        }

                        $xd = bcadd($xd,$newsXDMoney,2);
                        $bd = bcadd($bd,$budanMoney,2);
                        
                    }

                }

                $all = bcdiv(bcadd($xd,$bd,2),10000,2);
                $average = bcdiv($all,count($value['shop_list']),2);

                $xd = bcdiv($xd,10000,2);
                $bd = bcdiv($bd,10000,2);

                $xd_rate = (bcdiv($xd,$all,3)*100).'%';
                $bd_rate = (bcdiv($bd,$all,3)*100).'%';

                $price = $marketTask[$value['market_id']] ?? '0';
                $price = bcdiv($price,10000,0);
                $dachenglv = $price > 0 ? (bcdiv($all,$price,3)*100).'%' :'';

                $market[$key]['xd'] = $xd;
                $market[$key]['bd'] = $bd;
                $market[$key]['all'] = $all;
                $market[$key]['xd_rate'] = $xd_rate;
                $market[$key]['bd_rate'] = $bd_rate;
                $market[$key]['dachenglv'] = $dachenglv;
                $market[$key]['average'] = $average;
                $market[$key]['price'] = $price;
                // $market[$key]['price_base'] = $marketTask[$value['market_id']]['price_base'];

            }

            // echo "<pre>";
            // print_r($market);
            // echo "</pre>";
            // exit;
            $list = $market;

        }else{

            $shop_info = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_id,market_id,shop_name,shop_type,shop_othername','shop_id');

            foreach ($shop_info as $key => $value) {

                $xd = 0;
                $bd = 0;

                $v = $value['shop_id'];
                
                if($value['market_id'] == 8 || $value['market_id'] == 9 || $value['market_id'] == 10 || $value['market_id'] == 11){ // 川渝市场

                    $shopIds = [];

                    array_push($shopIds,$v);

                    $newsXDMoneyAll =$model->sumShopPayMoneyNewMZAll('XD',$shopIds,$start_time,$end_time);
                    $budanMoneyAll =$model->sumShopPayMoneyNewMZAll('BD',$shopIds,$start_time,$end_time);

                    $newsXDMoney = empty($newsXDMoneyAll[$v])?0:$newsXDMoneyAll[$v];
                    $budanMoney = empty($budanMoneyAll[$v])?0:$budanMoneyAll[$v];

                    $xd = bcadd($xd,$newsXDMoney,2);
                    $bd = bcadd($bd,$budanMoney,2);
    
                }else{ // 非川渝市场
    
                    $shopIds = [];

                    array_push($shopIds,$v);

                    if($value['shop_type'] == 1){

                        $newsXDMoneyAllOne =$model->sumShopPayMoneyNewAll('XD',$shopIds,1,$start_time,$end_time);
                        $budanMoneyAllOne =$model->sumShopPayMoneyNewAll('BD',$shopIds,1,$start_time,$end_time);

                        $newsXDMoney = empty($newsXDMoneyAllOne[$v])?0:$newsXDMoneyAllOne[$v];
                        $budanMoney = empty($budanMoneyAllOne[$v])?0:$budanMoneyAllOne[$v];

                    }else{

                        $newsXDMoneyAllTwo =$model->sumShopPayMoneyNewAll('XD',$shopIds,2,$start_time,$end_time);
                        $budanMoneyAllTwo =$model->sumShopPayMoneyNewAll('BD',$shopIds,2,$start_time,$end_time);

                        $newsXDMoney = empty($newsXDMoneyAllTwo[$v])?0:$newsXDMoneyAllTwo[$v];
                        $budanMoney = empty($budanMoneyAllTwo[$v])?0:$budanMoneyAllTwo[$v];

                    }

                    $xd = bcadd($xd,$newsXDMoney,2);
                    $bd = bcadd($bd,$budanMoney,2);
                        
                }


                $all = bcdiv(bcadd($xd,$bd,2),10000,2);

                $xd = bcdiv($xd,10000,2);
                $bd = bcdiv($bd,10000,2);

                $xd_rate = (bcdiv($xd,$all,3)*100).'%';
                $bd_rate = (bcdiv($bd,$all,3)*100).'%';
                

                // $price = bcdiv($marketTask[$value['market_id']]['price'],10000,1);
                // $avg_price = '';
                $shop_info[$key]['other_name'] = $value['shop_othername'];
                $shop_info[$key]['xd'] = $xd;
                $shop_info[$key]['bd'] = $bd;
                $shop_info[$key]['all'] = $all;
                $shop_info[$key]['rate'] = '';
                $shop_info[$key]['xd_rate'] = $xd_rate;
                $shop_info[$key]['bd_rate'] = $bd_rate;
                // $market[$key]['dachenglv'] = $dachenglv;
                // $market[$key]['average'] = $average;
                // $market[$key]['price'] = $price;
                // $market[$key]['price_base'] = $marketTask[$value['market_id']]['price_base'];

            }

            // echo "<pre>";
            // print_r($shop_info);
            // echo "</pre>";
            // exit;

            $list = $shop_info;

        }
        
        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";
        // exit;

        return [
            'list' => $list,
            'type' => $type,
        ];
    }


    // 疤痕项目业绩
    public function getScarAndProjectMoney($request)
    {
        $shop_ids = $request['shop_ids'] ?? [];

        $start_time = $request['start_time'] ?? 0;

        $end_time = $request['end_time'] ?? 0;

        $type = $request['type'] ?? '1';

        $start_time = strtotime($start_time);

        $end_time = strtotime($end_time)+86399;

        $market = $this->getMarketList($shop_ids);

        $startMonthTime = strtotime(date('Y-m',$start_time));

        $endMonthTime = strtotime(date('Y-m',$end_time));

        $market_ids = array_values(array_unique(array_column($market,'market_id')));

        // 市场任务
        //门店当月市场任务

        $marketTask =Db::name('shop_task')->field('sum(price) as price,sum(price_base) as price_base,market_id')

            ->where('month','>=',$startMonthTime)

            ->where('month','<=',$endMonthTime)

            ->where('market_id','in',$market_ids)

            ->group('market_id')
            
            // ->select()->toArray();

            ->column('price,price_base','market_id');

        $model = new ShopModel();

        $scarMoneyAll =$model->sumShopPayMoneyNewMZAll('Bh',$start_time,$end_time);

		$scarMoneyAllOne =$model->sumShopPayMoneyNewAll('Bh',1,$start_time,$end_time);

		$scarMoneyAllTwo =$model->sumShopPayMoneyNewAll('Bh',2,$start_time,$end_time);


        $projectMoneyAll =$model->sumShopPayMoneyNewMZAll('XM',$start_time,$end_time);

		$projectMoneyAllOne =$model->sumShopPayMoneyNewAll('XM',1,$start_time,$end_time);

		$projectMoneyAllTwo =$model->sumShopPayMoneyNewAll('XM',2,$start_time,$end_time);


        if($type == 1){

            
            foreach ($market as $key => $value) {

                $bh = 0;
                $xm = 0;

                if($value['market_id'] == 8 || $value['market_id'] == 9 || $value['market_id'] == 10 || $value['market_id'] == 11){ // 川渝市场

                    foreach ($value['shop_list'] as $k => $v) {

                        $scarMoney = empty($scarMoneyAll[$v])?0:$scarMoneyAll[$v];
				        $projectMoney = empty($projectMoneyAll[$v])?0:$projectMoneyAll[$v];

                        $bh = bcadd($bh,$scarMoney,2);
                        $xm = bcadd($xm,$projectMoney,2);

                    }
                    
                }else{ // 非川渝市场

                    foreach ($value['shop_list'] as $k => $v) {

                        $shopIds = [];

                        array_push($shopIds,$v);

                        $shop_type = Db::name('shop')->where('shop_id',$v)->value('shop_type');
                        
                        if($shop_type == 1){

                            $scarMoney = empty($scarMoneyAllOne[$v])?0:$scarMoneyAllOne[$v];
                            $projectMoney = empty($projectMoneyAllOne[$v])?0:$projectMoneyAllOne[$v];

                        }else{

                            $scarMoney = empty($scarMoneyAllTwo[$v])?0:$scarMoneyAllTwo[$v];
                            $projectMoney = empty($projectMoneyAllTwo[$v])?0:$projectMoneyAllTwo[$v];

                        }

                        $bh = bcadd($bh,$scarMoney,2);
                        $xm = bcadd($xm,$projectMoney,2);
                        
                    }

                }

                $all = bcdiv(bcadd($bh,$xm,2),10000,2);

                $bh = bcdiv($bh,10000,2);
                $xm = bcdiv($xm,10000,2);

                if($all > 0){
                    $bh_rate = (bcdiv($bh,$all,3)*100).'%';
                    $xm_rate = (bcdiv($xm,$all,3)*100).'%';
                }else{
                    $bh_rate = 0;
                    $xm_rate = 0;
                }

                $bh_rate = (bcdiv($bh,$all,3)*100).'%';
                $xm_rate = (bcdiv($xm,$all,3)*100).'%';

                $market[$key]['bh'] = $bh;
                $market[$key]['xm'] = $xm;
                $market[$key]['all'] = $all;
                $market[$key]['bh_rate'] = $bh_rate;
                $market[$key]['xm_rate'] = $xm_rate;

            }

            $list = $market;

        }else{

            $shop_info = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_id,market_id,shop_name,shop_type,shop_othername','shop_id');

            foreach ($shop_info as $key => $value) {

                $bh = 0;
                $xm = 0;

                $v = $value['shop_id'];
                
                if($value['market_id'] == 8 || $value['market_id'] == 9 || $value['market_id'] == 10 || $value['market_id'] == 11){ // 川渝市场

                    $scarMoney = empty($scarMoneyAll[$v])?0:$scarMoneyAll[$v];
				    $projectMoney = empty($projectMoneyAll[$v])?0:$projectMoneyAll[$v];

                    $bh = bcadd($xd,$newsXDMoney,2);
                    $xm = bcadd($bd,$budanMoney,2);
    
                }else{ // 非川渝市场
    
                    $shopIds = [];

                    array_push($shopIds,$v);

                    if($value['shop_type'] == 1){

                        $scarMoney = empty($scarMoneyAllOne[$v])?0:$scarMoneyAllOne[$v];
                        $projectMoney = empty($projectMoneyAllOne[$v])?0:$projectMoneyAllOne[$v];

                    }else{

                        $scarMoney = empty($scarMoneyAllTwo[$v])?0:$scarMoneyAllTwo[$v];
                        $projectMoney = empty($projectMoneyAllTwo[$v])?0:$projectMoneyAllTwo[$v];

                    }

                    $bh = bcadd($bh,$scarMoney,2);
                    $xm = bcadd($xm,$projectMoney,2);

                }

                $all = bcdiv(bcadd($bh,$xm,2),10000,2);

                $bh = bcdiv($bh,10000,2);
                $xm = bcdiv($xm,10000,2);

                if($all > 0){
                    $bh_rate = (bcdiv($bh,$all,3)*100).'%';
                    $xm_rate = (bcdiv($xm,$all,3)*100).'%';
                }else{
                    $bh_rate = 0;
                    $xm_rate = 0;
                }
                
                $shop_info[$key]['other_name'] = $value['shop_othername'];
                $shop_info[$key]['bh'] = $bh;
                $shop_info[$key]['xm'] = $xm;
                $shop_info[$key]['bh_rate'] = $bh_rate;
                $shop_info[$key]['xm_rate'] = $xm_rate;
                

            }

            // echo "<pre>";
            // print_r($shop_info);
            // echo "</pre>";
            // exit;

            $list = $shop_info;

        }
        

        return [
            'list' => $list,
            'type' => $type,
        ];

    }





    // --------------------------------------工具函数----------------------------
    public function getMarketList($shop_ids)
    {

        $market_list = Db::name('shop')->where('shop_id','in',$shop_ids)->column('market_id','shop_id');

        $shop_names = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name','shop_id');

        $market_ids = [];

        foreach ($market_list as $key => $value) {
            
            if(in_array($value,$market_ids)){

            }else{
                array_push($market_ids,$value);
            }

        }

        $market_name = Db::name('shop_market')->where([['id','in',$market_ids]])->column('name,other_name','id');

        $list = [];

        foreach ($market_ids as $key => $value) {

            $one = [];

            $one['market_id'] = $value;

            $one['market_name'] = $market_name[$value]['name'];

            $one['other_name'] = $market_name[$value]['other_name'];

            $one['shop_list'] = [];
            
            foreach ($market_list as $k => $v) {
                
                if($v == $value){

                    array_push($one['shop_list'],$k);

                }

            }

            array_push($list,$one);

        }

        return $list;
    }

    public function readAdminCustomerByShopId($request)
    {
        
        $start_time = $request['start_time'] ?? '';
        $end_time = $request['end_time'] ?? '';
        $shop_ids = $request['shop_ids'] ?? '';

        $ids = explode(',',$shop_ids);

        

        $model = new shopModel();
        $res = $model->getAdminShopStatistics($ids,$page=0,$limit=0,$request);

        echo "<pre>";
        print_r($res);
        echo "</pre>";
        exit;
        return $request;
    }

    
}